import * as VueRouter from 'vue-router'
import {useSysUserStore} from "../store/sys-user/index.js";
import Home from "../views/Home.vue";
import Login from "../views/Login.vue";
import {useSystemStore} from "../store/system/index.js";
import {profile} from "../apis/sys/user/index.js";
import {convertPathToCamelCase, transformMenuTree} from "../utils/index.js";
import routerComponent from "./routes.js";

const commonRoutes = [
    {
        meta: {
            title: '登录页'
        },
        path: "/login",
        name: "Login",
        component: Login
    },
    {
        path: "/",
        name: "Home",
        component: Home,
        redirect: '/dashboard',
        children: [
            {
                meta: {
                    title: '仪表盘'
                },
                path: "/dashboard",
                name: "Dashboard",
                component: () => import('../views/dashboard/index.vue'),
            }
        ]
    }
]

const router = VueRouter.createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: VueRouter.createWebHashHistory(),
    // 路由结果等于公共页面 + 业务页面共同构成
    routes: commonRoutes // `routes: routes` 的缩写
})
// 导航路由
router.beforeEach(async (to, from, next) => {
    const sysUserStore = useSysUserStore()
    const systemStore = useSystemStore()
    // 如果是非公共组件 则在tab页上进行展示
    if (!commonRoutes.find(item => to.name === item.name)) {
        if (router.hasRoute(to.name)) {
            await systemStore.routerPush(to)
        }
    }
    // 如果访问的是非登录 且未登录，则跳转到登录页面
    if (to.name !== 'Login' && !sysUserStore.isLogin) {
        next({name: 'Login'})
        return
    }
    if (to.name !== 'Login' && !sysUserStore.hasUserInfo) {
        await loadProfile();
        next({...to, replace: true})
        return
    }
    // 如果访问的是登录，且已登录 则直接进入首页
    if (to.name === 'Login' && sysUserStore.isLogin) {
        next({name: 'Home'})
        return
    }
    // 其他情况一律直接放行
    next()
})

const loadProfile = async () => {
    const sysUserStore = useSysUserStore()
    const systemStore = useSystemStore()
    const res = await profile()
    if (res.data.code === 1) {
        const user = res.data.data
        const menuList = user.sysMenuList
        await sysUserStore.initUserInfo({
            nickname: user.nickname
        })
        if (menuList && menuList.length > 0) {
            // 初始化菜单树状结构
            await systemStore.initMenuTree(transformMenuTree(menuList))
            // 初始化动态路由
            const routes = findAndTransformRoutes(menuList);
            routes.forEach(route => router.addRoute('Home', route))
        }
    }
}


/**
 * 遍历查询所有的路由信息
 * @param source
 * @returns {*[]}
 */
export const findAndTransformRoutes = (source) => {
    let routes = []
    source.forEach(item => {
        if (item.menuType === 'C') {
            routes.push({
                meta: {
                    title: item.menuName
                },
                path: item.path,
                name: convertPathToCamelCase(item.path),
                component: routerComponent[item.component]
            })
        }
        if (item.children) {
            routes = routes.concat(findAndTransformRoutes(item.children))
        }
    })
    return routes
}


export default router
